package com.ee.chat.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ee.chat.admin.service.IIndexService;
import com.ee.chat.admin.service.ILoginService;
import com.ee.chat.admin.service.IOperationService;
import com.ee.chat.common.bean.Result;
import com.ee.chat.common.dao.AdminUserMapper;
import com.ee.chat.common.entity.AdminUser;
import com.ndhutu.ee.util.MD5Util;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class LoginServiceImpl implements ILoginService {
    @Resource
    AdminUserMapper adminUserMapper;
    @Resource
    IIndexService indexService;
    @Resource
    IOperationService operationService;

    @Override
    public Result login(HttpServletRequest request, String username, String password) throws Exception {
        HttpSession session = request.getSession(true);

        QueryWrapper<AdminUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        AdminUser adminUser = adminUserMapper.selectOne(wrapper);
        if(adminUser == null || !MD5Util.encode32(password).equals(adminUser.getPassword())){
            return Result.returnFailure("用户名密码错误");
        }
        if(adminUser.getStatus() != 0){
            return Result.returnFailure("账号已禁用");
        }

        int userId = adminUser.getId();
        List<String> userPermissions, permissions;
        if(adminUser.getSystem() == 1){    //系统内置超级管理员
            userPermissions = indexService.getUserPermissions(null);
        }else{
            userPermissions = indexService.getUserPermissions(userId);
        }
        permissions = indexService.getUserPermissions(null);

        session.setAttribute("adminUser", adminUser);
        session.setAttribute("permissions", permissions);
        session.setAttribute("userPermissions", userPermissions);

        operationService.addOperationLog(request, "登录成功");

        return Result.returnSuccess(null);
    }

    @Override
    public Result updPwd(HttpServletRequest request, String oldPwd, String newPwd) throws Exception {
        HttpSession session = request.getSession(true);
        AdminUser adminUser = (AdminUser) session.getAttribute("adminUser");

        if(!adminUser.getPassword().equals(MD5Util.encode32(oldPwd))){
            return Result.returnFailure("原密码错误，请重新填写");
        }

        adminUser.setPassword(MD5Util.encode32(newPwd));
        adminUserMapper.updateById(adminUser);
        session.setAttribute("adminUser", adminUser);

        operationService.addOperationLog(request, "更新密码");

        return Result.returnSuccess(null);
    }
}
